package com.bbcare.followup.plat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.*;
import com.bbcare.comm.enumeration.MessageTypeEnum;
import com.bbcare.department.plat.entity.Contact;
import com.bbcare.followup.plat.entity.*;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IXCXService;
import com.bbcare.followup.plat.store.ibatis.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对接小程序服务端的服务类。
 */
@Service
public class XCXServiceImpl implements IXCXService {
    private static Logger logger = Logger.getLogger(XCXServiceImpl.class);

    @Autowired
    private IFollowQueueService followQueueSerivce;

    @Autowired
    private IConfCacheDAO confCacheDao;

    @Autowired
    private IPatientDAO patientDao;

    @Autowired
    private IPatientTaskDAO patientTaskDao;

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;

    @Autowired
    private IMessageNotifyRecordDAO msgDao;


    @Override
    public void checkRequest_addnewpatient(final String requestParams) throws Exception {
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(requestParams);
        } catch (Exception ex) {
            logger.error(ex.getStackTrace().toString());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String queueId = jsonData.getString("queueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入queueId或值为空！"));
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", queueId);
        FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
        if (null == queue) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据queueId参数查询无此队列信息！"));
        }

    }

    //查询患者窗口期任务list。
    @Override
    public List<PatientTask> queryWindowTasks(final Map<String, Object> paramIn) throws Exception {
        Map<String, Object> argMap  = new HashMap<String, Object>(paramIn);
        List<PatientTask> taskList  = patientTaskDao.queryXcxWinTask(argMap);
        return taskList;
    }

    /**
     * 保存1个患者的下次检查提醒消息（小程序）。
     * @param task
     * @return
     * @throws Exception
     */
    public boolean insertXcxMsg(final PatientTask task) throws Exception  {
        Patient pat = null;
        Map<String, Object> paraMap = new HashMap<String, Object>();
        final String patUserId  = task.getUserId();
        paraMap.put("userId", patUserId);
        List<Patient> patList = patientDao.select(paraMap);
        if (null == patList || patList.isEmpty())    {
            logger.error("----insertXcxMsg() 发生查询患者错误，患者ID:"+patUserId+"没有找到！！");
            return false;
        } else {
            pat = patList.get(0);
        }

        MessageNotifyRecord wxMsg   = new MessageNotifyRecord();
        wxMsg.setId(task.getId());
        wxMsg.setType(MessageTypeEnum.XCJCTX.getValue());
        wxMsg.setStatus(2); //1已读，2未读。
        wxMsg.setUserId(pat.getId());
        wxMsg.setUserName(pat.getUserName());
        wxMsg.setGender(pat.getGender());
        wxMsg.setPhone(pat.getPhoneNo());
        wxMsg.setAccountId(pat.getAccountId());
        wxMsg.setTenantId(pat.getTenantId());
        wxMsg.setTaskId(task.getId());
        wxMsg.setTaskName(task.getTaskName());
        wxMsg.setCreateTime(DateUtil.getDate(DateUtil.getCurrDate2()));
        wxMsg.setRemark(MessageTypeEnum.XCJCTX.getName());
        int inserted = msgDao.insert(wxMsg);
        if (1 == inserted)  {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查询患者的下次检查提醒消息。
     * @param tenantId
     * @param patId
     * @return
     */
    public List<Map<String,Object>> queryXCJCTXmsg(final String tenantId, final String patId) throws Exception {
        logger.info("++++queryXCJCTXmsg() parameter tenantId:"+tenantId+", patientId:"+patId);
        HashMap<String, Object> paraMap = new HashMap<String, Object>();
        paraMap.put("tenantId", tenantId);
        paraMap.put("userId",   patId);
        List<MessageNotifyRecord> msgList   = msgDao.selectByPat(paraMap);
        java.util.Date now = new java.util.Date();
        String genderCn,taskId,queueId;
        List<Map<String,Object>> retList    = new ArrayList<>();
        if (null != msgList && !msgList.isEmpty())  {
            final MessageNotifyRecord msg   = msgList.get(0);
            taskId  = msg.getTaskId();
            paraMap.clear();
            paraMap.put("taskId",taskId);
            queueId = patientTaskDao.selectById(paraMap).get(0).getQueueId();
            if (msg.getGender().equalsIgnoreCase("N") || msg.getGender().equalsIgnoreCase("M")) {
                genderCn = "男";
            } else {
                genderCn = "女";
            }
            HashMap<String, Object> rowMap  = new HashMap<String, Object>();
            rowMap.put("pt_account_id", msg.getAccountId());
            rowMap.put("pt_user_id",    patId);
            rowMap.put("type",  0);   //通知消息。
            rowMap.put("task_id",   taskId);
            rowMap.put("queue_id",  queueId);
            rowMap.put("business_id",msg.getTaskId());
            rowMap.put("task_name", msg.getTaskName());
            rowMap.put("remark",    "姓名："+msg.getUserName()+"，性别："+genderCn+"，电话："+msg.getPhone());
            rowMap.put("alias", PropertiesUtils.getProperty("gy3y_msg_xcjctx_alias"));
            rowMap.put("title", PropertiesUtils.getProperty("gy3y_msg_xcjctx_title"));
            rowMap.put("body",  PropertiesUtils.getProperty("gy3y_msg_xcjctx_body"));
            retList.add(rowMap);

            msg.setSendTime(now);
            msg.setUpdateTime(now);
            msgDao.updateByPrimaryKey(msg);
        }

        return retList;
    }
}
